package com.plat.controller;

import java.io.InputStream;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import net.sf.json.JSONObject;

import org.activiti.bpmn.model.BpmnModel;
import org.activiti.engine.RepositoryService;
import org.activiti.engine.RuntimeService;
import org.activiti.engine.TaskService;
import org.activiti.engine.impl.bpmn.diagram.ProcessDiagramGenerator;
import org.activiti.engine.impl.context.Context;
import org.activiti.engine.runtime.ProcessInstance;
import org.activiti.spring.ProcessEngineFactoryBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.propertyeditors.CustomDateEditor;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.InitBinder;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import com.plat.security.entity.Leave;
import com.plat.security.entity.SysUsers;
import com.plat.service.ILeave;
import com.plat.tag.core.json.AjaxJson;
import com.plat.tag.core.json.AjaxUtils;
import com.plat.tag.core.json.DataGrid;
import com.plat.tag.core.utils.TagUtil;
import com.plat.util.Variable;

@Controller
@RequestMapping("/leaveController.do")
public class LeaveController extends BaseController<Leave> {

	@Autowired
	private ILeave service;

	@Autowired
	protected TaskService taskService;

	@Autowired
	private RuntimeService runtimeService;

	@Autowired
	protected RepositoryService repositoryService;

	@Autowired
	ProcessEngineFactoryBean processEngine;

	@Override
	public ILeave getService() {
		return service;
	}

	@InitBinder
	public void initBinder(WebDataBinder binder) {
		binder.registerCustomEditor(Date.class,
				new CustomDateEditor(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"), false));
	}

	@RequestMapping(params = "strat")
	@ResponseBody
	public AjaxJson startWorkflow(Leave leave, HttpServletRequest request, RedirectAttributes redirectAttributes) {
		AjaxJson j = new AjaxJson();
		j.setMsg("添加成功");
		try {
			SysUsers user = getUserDetails(request);

			leave.setUserId(user.getUserId());
			Map<String, Object> variables = new HashMap<String, Object>();

			ProcessInstance process = getService().saveWorkflow(leave, variables);
			redirectAttributes.addFlashAttribute("message", "流程已启动，流程ID：" + process.getId());
		} catch (Exception e) {
			j.setSuccess(false);
			j.setMsg("添加失败");
			e.printStackTrace();
		}
		return j;
	}

	/**
	 * 查询待办的任务
	 * @param session
	 * @param request
	 * @param dataGrid
	 * @return
	 */
	@RequestMapping(params = "taskList")
	@ResponseBody
	public String taskList(HttpSession session, HttpServletRequest request, DataGrid dataGrid) {

		try {
			SysUsers user = getUserDetails(request);
			List<Leave> reaults = getService().findTodoTasks(user.getUserId().toString(), dataGrid,
					getSessionRoles(request));
			dataGrid.setReaults(reaults);
			dataGrid.setTotal(reaults.size());
			JSONObject object = TagUtil.getJson(dataGrid);
			return object.toString();
		} catch (Exception e) {
			e.printStackTrace();
		}
		return "{}";
	}

	/**
	 * 查询已经运行的流程任务
	 * @param session
	 * @param request
	 * @param dataGrid
	 * @return
	 */
	@RequestMapping(params = "runList")
	@ResponseBody
	public String findRunningProcessInstaces(HttpSession session, HttpServletRequest request, DataGrid dataGrid) {

		try {
			List<Leave> reaults = getService().findRunningProcessInstaces(dataGrid, getSessionAuthorities(request));
			dataGrid.setReaults(reaults);
			dataGrid.setTotal(reaults.size());

			JSONObject object = TagUtil.getJson(dataGrid);
			return object.toString();
		} catch (Exception e) {
			e.printStackTrace();
		}
		return "{}";
	}

	/**
	 * 查询待办的任务
	 * @param session
	 * @param request
	 * @param dataGrid
	 * @return
	 */
	@RequestMapping(params = "finishedList")
	@ResponseBody
	public String finishedList(HttpSession session, HttpServletRequest request, DataGrid dataGrid) {

		try {
			List<Leave> reaults = getService().findFinishedProcessInstaces();
			dataGrid.setReaults(reaults);
			dataGrid.setTotal(reaults.size());
			JSONObject object = TagUtil.getJson(dataGrid);
			return object.toString();
		} catch (Exception e) {
			e.printStackTrace();
		}
		return "{}";
	}

	/**
	 * 签收任务
	 */
	@RequestMapping(params = "claim")
	@ResponseBody
	public AjaxJson claim(final String taskId, HttpServletRequest request) {
		final SysUsers user = getUserDetails(request);
		return new AjaxUtils() {

			@Override
			protected Object busCall() throws Exception {
				taskService.claim(taskId, user.getUserId());
				return null;
			}
		}.excuteJson("签收成功!", "签收失败!");
	}

	/**
	 * 完成任务
	 * 
	 * @param id
	 * @return
	 */
	@RequestMapping(params = "complete", method = { RequestMethod.POST, RequestMethod.GET })
	@ResponseBody
	public AjaxJson complete(String taskId, Variable var) {
		try {
			Map<String, Object> variables = var.getVariableMap();
			taskService.complete(taskId, variables);
		} catch (Exception e) {
			e.printStackTrace();
		}

		return new AjaxUtils() {

			protected Object busCall() throws Exception {
				return null;
			};
		}.excuteJson("审批成功!", "审批失败!");
	}

	/**
	 * 读取带跟踪的图片
	 */
	@RequestMapping(params = "workflow")
	public void readResource(String executionId, HttpServletResponse response) throws Exception {
		ProcessInstance processInstance = runtimeService.createProcessInstanceQuery().processInstanceId(executionId)
				.singleResult();
		BpmnModel bpmnModel = repositoryService.getBpmnModel(processInstance.getProcessDefinitionId());
		List<String> activeActivityIds = runtimeService.getActiveActivityIds(executionId);
		// 不使用spring请使用下面的两行代码
		// ProcessEngineImpl defaultProcessEngine = (ProcessEngineImpl) ProcessEngines.getDefaultProcessEngine();
		// Context.setProcessEngineConfiguration(defaultProcessEngine.getProcessEngineConfiguration());

		// 使用spring注入引擎请使用下面的这行代码
		Context.setProcessEngineConfiguration(processEngine.getProcessEngineConfiguration());

		InputStream imageStream = ProcessDiagramGenerator.generateDiagram(bpmnModel, "png", activeActivityIds);

		// 输出资源内容到相应对象
		byte[] b = new byte[1024];
		int len;
		while ((len = imageStream.read(b, 0, 1024)) != -1) {
			response.getOutputStream().write(b, 0, len);
		}
	}
}
